<template>
  <div class="role-manage">
    <div class="page-header">
      <h2>角色管理</h2>
      <p>管理系统角色和权限分配</p>
    </div>

    <!-- 操作栏 -->
    <div class="action-bar">
      <button @click="openAddDialog" class="btn-add">
        <span>+ 添加角色</span>
      </button>
    </div>

    <!-- 角色列表 -->
    <div class="role-grid">
      <div 
        v-for="role in roles" 
        :key="role.id" 
        class="role-card"
        :class="{ 'system-role': isSystemRole(role) }"
      >
        <div class="role-header">
          <div class="role-info">
            <h3>{{ role.roleName }}</h3>
            <span class="role-code">{{ role.roleCode }}</span>
          </div>
          <div class="role-status">
            <span 
              class="status-dot" 
              :class="role.status === 1 ? 'active' : 'inactive'"
            ></span>
            {{ role.status === 1 ? '启用' : '禁用' }}
          </div>
        </div>
        
        <div class="role-description">
          {{ role.description || '暂无描述' }}
        </div>
        
        <div class="role-permissions">
          <h4>权限列表</h4>
          <div class="permission-tags">
            <span 
              v-for="perm in getRolePermissions(role.id)" 
              :key="perm.id"
              class="permission-tag"
            >
              {{ perm.permissionName }}
            </span>
            <span v-if="getRolePermissions(role.id).length === 0" class="no-data">
              暂无权限
            </span>
          </div>
        </div>
        
        <div class="role-footer">
          <button @click="openPermissionDialog(role)" class="btn-permission">
            分配权限
          </button>
          <button 
            v-if="!isSystemRole(role)" 
            @click="openEditDialog(role)" 
            class="btn-edit"
          >
            编辑
          </button>
          <button 
            v-if="!isSystemRole(role)" 
            @click="deleteRole(role)" 
            class="btn-delete"
          >
            删除
          </button>
        </div>
      </div>
    </div>

    <!-- 添加/编辑角色对话框 -->
    <div v-if="showRoleDialog" class="modal-overlay" @click.self="closeRoleDialog">
      <div class="modal-content">
        <div class="modal-header">
          <h3>{{ isEdit ? '编辑角色' : '添加角色' }}</h3>
          <button @click="closeRoleDialog" class="close-btn">&times;</button>
        </div>
        <div class="modal-body">
          <div class="form-group">
            <label>角色编码 *</label>
            <input 
              v-model="roleForm.roleCode" 
              type="text" 
              placeholder="例如: REVIEWER"
              :disabled="isEdit"
            />
          </div>
          <div class="form-group">
            <label>角色名称 *</label>
            <input 
              v-model="roleForm.roleName" 
              type="text" 
              placeholder="例如: 审核员"
            />
          </div>
          <div class="form-group">
            <label>角色描述</label>
            <textarea 
              v-model="roleForm.description" 
              placeholder="描述该角色的职责和权限"
              rows="3"
            ></textarea>
          </div>
          <div class="form-group">
            <label>状态</label>
            <select v-model="roleForm.status">
              <option :value="1">启用</option>
              <option :value="0">禁用</option>
            </select>
          </div>
        </div>
        <div class="modal-footer">
          <button @click="submitRole" class="btn-primary">
            {{ isEdit ? '保存' : '添加' }}
          </button>
          <button @click="closeRoleDialog" class="btn-cancel">取消</button>
        </div>
      </div>
    </div>

    <!-- 权限分配对话框 -->
    <div v-if="showPermissionDialog" class="modal-overlay" @click.self="closePermissionDialog">
      <div class="modal-content">
        <div class="modal-header">
          <h3>为 {{ currentRole.roleName }} 分配权限</h3>
          <button @click="closePermissionDialog" class="close-btn">&times;</button>
        </div>
        <div class="modal-body">
          <div class="current-permissions">
            <h4>当前权限：</h4>
            <div class="permission-list-current">
              <div 
                v-for="perm in rolePermissions" 
                :key="perm.id"
                class="permission-item current"
              >
                <span>{{ perm.permissionName }} ({{ perm.permissionCode }})</span>
                <button @click="removePermission(perm)" class="btn-remove">移除</button>
              </div>
              <div v-if="rolePermissions.length === 0" class="no-data">
                暂无权限
              </div>
            </div>
          </div>
          <div class="available-permissions">
            <h4>可分配权限：</h4>
            <div class="permission-list-available">
              <label 
                v-for="perm in availablePermissions" 
                :key="perm.id"
                class="permission-checkbox"
              >
                <input 
                  type="checkbox" 
                  :value="perm.id" 
                  v-model="selectedPermissions"
                />
                <div class="permission-info">
                  <span class="permission-name">{{ perm.permissionName }}</span>
                  <span class="permission-code">{{ perm.permissionCode }}</span>
                  <span class="permission-type">{{ perm.resourceType }}</span>
                </div>
              </label>
            </div>
          </div>
        </div>
        <div class="modal-footer">
          <button @click="assignPermissions" class="btn-primary">确定分配</button>
          <button @click="closePermissionDialog" class="btn-cancel">取消</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import * as adminAPI from '@/api/admin'

const roles = ref([])
const permissions = ref([])
const rolePermissionsMap = ref({})

const showRoleDialog = ref(false)
const showPermissionDialog = ref(false)
const isEdit = ref(false)
const currentRole = ref(null)
const rolePermissions = ref([])
const selectedPermissions = ref([])

const roleForm = ref({
  roleCode: '',
  roleName: '',
  description: '',
  status: 1
})

// 可分配的权限（排除已有的）
const availablePermissions = computed(() => {
  const rolePermIds = rolePermissions.value.map(p => p.id)
  return permissions.value.filter(p => !rolePermIds.includes(p.id))
})

// 获取角色的权限列表
const getRolePermissions = (roleId) => {
  return rolePermissionsMap.value[roleId] || []
}

// 判断是否为系统角色
const isSystemRole = (role) => {
  return ['SUPER_ADMIN', 'ADMIN', 'USER'].includes(role.roleCode)
}

// 加载角色列表
const loadRoles = async () => {
  try {
    const res = await adminAPI.getAllRoles()
    if (res.code === 200) {
      roles.value = res.data || []
      // 加载每个角色的权限
      roles.value.forEach(role => {
        loadRolePermissions(role.id)
      })
    }
  } catch (error) {
    ElMessage.error('获取角色列表失败')
  }
}

// 加载权限列表
const loadPermissions = async () => {
  try {
    const res = await adminAPI.getAllPermissions()
    if (res.code === 200) {
      permissions.value = res.data || []
    }
  } catch (error) {
    ElMessage.error('获取权限列表失败')
  }
}

// 加载角色的权限
const loadRolePermissions = async (roleId) => {
  try {
    const res = await adminAPI.getRolePermissions(roleId)
    if (res.code === 200) {
      rolePermissionsMap.value[roleId] = res.data || []
    }
  } catch (error) {
    console.error('获取角色权限失败', error)
  }
}

// 打开添加对话框
const openAddDialog = () => {
  isEdit.value = false
  roleForm.value = {
    roleCode: '',
    roleName: '',
    description: '',
    status: 1
  }
  showRoleDialog.value = true
}

// 打开编辑对话框
const openEditDialog = (role) => {
  isEdit.value = true
  roleForm.value = { ...role }
  showRoleDialog.value = true
}

// 关闭角色对话框
const closeRoleDialog = () => {
  showRoleDialog.value = false
  roleForm.value = {
    roleCode: '',
    roleName: '',
    description: '',
    status: 1
  }
}

// 提交角色
const submitRole = async () => {
  if (!roleForm.value.roleCode || !roleForm.value.roleName) {
    ElMessage.warning('请填写必填项')
    return
  }
  
  try {
    const api = isEdit.value ? adminAPI.updateRole : adminAPI.addRole
    const res = await api(roleForm.value)
    
    if (res.code === 200) {
      ElMessage.success(isEdit.value ? '更新角色成功' : '添加角色成功')
      closeRoleDialog()
      loadRoles()
    } else {
      ElMessage.error(res.msg || '操作失败')
    }
  } catch (error) {
    ElMessage.error('操作失败')
  }
}

// 删除角色
const deleteRole = async (role) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除角色 ${role.roleName} 吗？此操作将同时删除该角色的所有关联！`, 
      '警告', 
      {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'error'
      }
    )
    
    const res = await adminAPI.deleteRole(role.id)
    if (res.code === 200) {
      ElMessage.success('删除角色成功')
      loadRoles()
    } else {
      ElMessage.error(res.msg || '删除角色失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除角色失败')
    }
  }
}

// 打开权限分配对话框
const openPermissionDialog = async (role) => {
  currentRole.value = role
  selectedPermissions.value = []
  try {
    const res = await adminAPI.getRolePermissions(role.id)
    if (res.code === 200) {
      rolePermissions.value = res.data || []
      showPermissionDialog.value = true
    }
  } catch (error) {
    ElMessage.error('获取角色权限失败')
  }
}

// 关闭权限对话框
const closePermissionDialog = () => {
  showPermissionDialog.value = false
  currentRole.value = null
  rolePermissions.value = []
  selectedPermissions.value = []
}

// 移除权限
const removePermission = async (permission) => {
  try {
    await ElMessageBox.confirm(`确定要移除 ${permission.permissionName} 权限吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const res = await adminAPI.removeRolePermission({
      roleId: currentRole.value.id,
      permissionId: permission.id
    })
    
    if (res.code === 200) {
      ElMessage.success('移除权限成功')
      openPermissionDialog(currentRole.value)
      loadRolePermissions(currentRole.value.id)
    } else {
      ElMessage.error(res.msg || '移除权限失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('移除权限失败')
    }
  }
}

// 分配权限
const assignPermissions = async () => {
  if (selectedPermissions.value.length === 0) {
    ElMessage.warning('请选择要分配的权限')
    return
  }
  
  try {
    for (const permId of selectedPermissions.value) {
      await adminAPI.assignPermissionToRole({
        roleId: currentRole.value.id,
        permissionId: permId
      })
    }
    ElMessage.success('分配权限成功')
    closePermissionDialog()
    loadRolePermissions(currentRole.value.id)
  } catch (error) {
    ElMessage.error('分配权限失败')
  }
}

onMounted(() => {
  loadRoles()
  loadPermissions()
})
</script>

<style scoped>
.role-manage {
  padding: 20px;
  background: #f5f5f5;
  min-height: calc(100vh - 60px);
}

.page-header {
  background: white;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.page-header h2 {
  margin: 0 0 10px 0;
  color: #333;
}

.page-header p {
  margin: 0;
  color: #666;
  font-size: 14px;
}

.action-bar {
  background: white;
  padding: 15px 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.btn-add {
  padding: 10px 20px;
  background: #42b983;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  display: flex;
  align-items: center;
  gap: 5px;
}

.btn-add:hover {
  background: #3aa876;
}

.role-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
  gap: 20px;
}

.role-card {
  background: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  transition: all 0.3s;
}

.role-card:hover {
  box-shadow: 0 4px 12px rgba(0,0,0,0.15);
  transform: translateY(-2px);
}

.system-role {
  border: 2px solid #ffd700;
  position: relative;
}

.system-role::before {
  content: '系统角色';
  position: absolute;
  top: 10px;
  right: 10px;
  padding: 2px 8px;
  background: #ffd700;
  color: #333;
  font-size: 12px;
  border-radius: 10px;
}

.role-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 15px;
  padding-bottom: 15px;
  border-bottom: 1px solid #eee;
}

.role-info h3 {
  margin: 0 0 5px 0;
  color: #333;
  font-size: 18px;
}

.role-code {
  display: inline-block;
  padding: 2px 8px;
  background: #e3f2fd;
  color: #1976d2;
  border-radius: 10px;
  font-size: 12px;
  font-family: monospace;
}

.role-status {
  display: flex;
  align-items: center;
  gap: 5px;
  font-size: 13px;
  color: #666;
}

.status-dot {
  width: 8px;
  height: 8px;
  border-radius: 50%;
}

.status-dot.active {
  background: #4caf50;
}

.status-dot.inactive {
  background: #f44336;
}

.role-description {
  color: #666;
  font-size: 14px;
  line-height: 1.6;
  margin-bottom: 15px;
  min-height: 40px;
}

.role-permissions {
  margin-bottom: 15px;
}

.role-permissions h4 {
  margin: 0 0 10px 0;
  color: #333;
  font-size: 14px;
  font-weight: 600;
}

.permission-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.permission-tag {
  padding: 4px 10px;
  background: #e8f5e9;
  color: #2e7d32;
  border-radius: 10px;
  font-size: 12px;
}

.role-footer {
  display: flex;
  gap: 8px;
  padding-top: 15px;
  border-top: 1px solid #eee;
}

.role-footer button {
  flex: 1;
  padding: 8px 12px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 13px;
  transition: all 0.3s;
}

.btn-permission {
  background: #2196f3;
  color: white;
}

.btn-permission:hover {
  background: #1976d2;
}

.btn-edit {
  background: #ff9800;
  color: white;
}

.btn-edit:hover {
  background: #f57c00;
}

.btn-delete {
  background: #f44336;
  color: white;
}

.btn-delete:hover {
  background: #d32f2f;
}

/* 模态框样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0,0,0,0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal-content {
  background: white;
  border-radius: 8px;
  width: 90%;
  max-width: 600px;
  max-height: 80vh;
  overflow: auto;
}

.modal-header {
  padding: 20px;
  border-bottom: 1px solid #eee;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.modal-header h3 {
  margin: 0;
  color: #333;
}

.close-btn {
  background: none;
  border: none;
  font-size: 28px;
  color: #999;
  cursor: pointer;
  padding: 0;
  width: 30px;
  height: 30px;
  line-height: 1;
}

.close-btn:hover {
  color: #333;
}

.modal-body {
  padding: 20px;
}

.form-group {
  margin-bottom: 15px;
}

.form-group label {
  display: block;
  margin-bottom: 5px;
  color: #333;
  font-size: 14px;
  font-weight: 500;
}

.form-group input,
.form-group textarea,
.form-group select {
  width: 100%;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
  font-family: inherit;
}

.form-group input:focus,
.form-group textarea:focus,
.form-group select:focus {
  outline: none;
  border-color: #42b983;
}

.current-permissions,
.available-permissions {
  margin-bottom: 20px;
}

.current-permissions h4,
.available-permissions h4 {
  margin: 0 0 10px 0;
  color: #333;
  font-size: 14px;
}

.permission-list-current,
.permission-list-available {
  max-height: 300px;
  overflow-y: auto;
}

.permission-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
  margin-bottom: 8px;
}

.permission-item.current {
  background: #e8f5e9;
  border-color: #4caf50;
}

.btn-remove {
  padding: 4px 10px;
  background: #f44336;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 12px;
}

.btn-remove:hover {
  background: #d32f2f;
}

.permission-checkbox {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  margin-bottom: 8px;
  cursor: pointer;
  transition: all 0.3s;
}

.permission-checkbox:hover {
  background: #f5f5f5;
  border-color: #42b983;
}

.permission-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.permission-name {
  color: #333;
  font-size: 14px;
  font-weight: 500;
}

.permission-code {
  color: #666;
  font-size: 12px;
  font-family: monospace;
}

.permission-type {
  color: #999;
  font-size: 12px;
}

.no-data {
  color: #999;
  font-size: 13px;
}

.modal-footer {
  padding: 15px 20px;
  border-top: 1px solid #eee;
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.btn-primary {
  padding: 8px 20px;
  background: #42b983;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
}

.btn-primary:hover {
  background: #3aa876;
}

.btn-cancel {
  padding: 8px 20px;
  background: #f5f5f5;
  color: #666;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
}

.btn-cancel:hover {
  background: #e0e0e0;
}
</style>

